<template>
  <el-upload
    ref="elUpload"
    class="uploadBtn"
    action=""
    :limit="limit"
    :http-request="uploadBefore"
    :auto-upload="true"
    :show-file-list="false"
    :multiple="multiple"
  >
    <el-button size="small" type="primary">{{ name }}</el-button>
  </el-upload>
</template>

<script>
import axios from 'axios'
import { getPolicy } from '@/api/common'
export default {
  props: {
    limit: {
      required: false,
      type: Number,
      default: 999999
    },
    multiple: {
      required: false,
      type: Boolean,
      default: false
    },
    name: {
      required: false,
      type: String,
      default: '点击上传'
    },
    fileFilter: {
      required: false,
      type: Array,
      default: () => []
    },
    widthSize: {
      required: false,
      type: Number,
      default: 0
    },
    heightSize: {
      required: false,
      type: Number,
      default: 0
    },
    maxSize: {
      required: false,
      type: Number,
      default: 0
    }
  },
  data() {
    return {
      filterImgType: ['jpg', 'jpeg', 'png', 'icon', 'gif', 'bmp', 'JPG', 'JPEG', 'PNG', 'ICON', 'GIF', 'BMP']
    }
  },
  methods: {
    uploadBefore(file) {
      if (this.fileFilter.length > 0 && !this.fileFilter.find(item => file.file.type.indexOf(item) > -1)) {
        this.$refs.elUpload.uploadFiles = this.$refs.elUpload.uploadFiles.filter(item => item.uid !== file.file.uid)
        this.$message.error('上传文件格式不正确,请重新上传')
        return
      }
      if (this.maxSize !== 0 && file.file.size / 1024 / 1024 > this.maxSize) {
        this.$refs.elUpload.uploadFiles = this.$refs.elUpload.uploadFiles.filter(item => item.uid !== file.file.uid)
        this.$message.error(`文件最大上传${this.maxSize}M`)
        return
      }
      if (this.filterImgType.find(item => file.file.type.indexOf(item) > -1) && this.widthSize !== 0 && this.heightSize !== 0) {
        const _this = this
        new Promise(function(resolve, reject) {
          const _URL = window.URL || window.webkitURL
          var img = new Image()
          img.onload = function() {
            const valid = img.width === _this.widthSize && img.height === _this.heightSize
            valid ? resolve() : reject()
          }
          img.src = _URL.createObjectURL(file.file)
        }).then(() => {
          this.uploadFile(file)
        }, () => {
          this.$refs.elUpload.uploadFiles = this.$refs.elUpload.uploadFiles.filter(item => item.uid !== file.file.uid)
          this.$message.error(`上传图片分辨率为${this.widthSize}*${this.heightSize}`)
          return Promise.reject()
        })
      } else {
        this.uploadFile(file)
      }
    },
    uploadFile(file) {
      getPolicy({}, 'get').then(response => {
        const formData = new FormData()
        // const name = response.dir + new Date().getTime() + '_' + file.file.name.split('.')[0] + '.' + file.file.name.split('.')[1]
        const pattern=/[`~!@#$^&*()=|{}':;',\\\[\]\.<>\/?~！@#￥……&*（）——|{}【】'；：""'。，、？\s]/g;
        // const name = response.dir  + new Date().getTime() + '_' + file.file.name.split('.')[0].replace(pattern,"")  + '.' + file.file.name.split('.')[1]
         const name = response.dir  + new Date().getTime() + '_' + file.file.name.slice(0,file.file.name.lastIndexOf('.')).replace(pattern,"")  + '.' + file.file.name.slice(file.file.name.lastIndexOf('.')+1)
        formData.append('policy', response.policy)
        formData.append('OSSAccessKeyId', response.accessId)
        formData.append('success_action_status', '200')
        formData.append('signature', response.signature)
        formData.append('key', name)
        formData.append('file', file.file)
        formData.append('type', file.file.type)
        if (response.callback !== null) {
          formData.append('callback', response.callback)
        }
        axios({
          url: response.host,
          method: 'POST',
          headers: { 'content-type': 'application/x-www-form-urlencoded' },
          data: formData
        }).then(res => {
          // this.$emit('setUrl', name, file.file.name, response.host)
          this.$emit('setUrl', name, file.file.name.replace(pattern,""), response.host)
          this.$message.success('上传成功')
        }).catch(err => {
          this.$message.error(err.msg)
        })
      })
    }
  }
}
</script>

<style>

</style>
